<template>

  <a-radio-group v-if="isRadio" v-model="selected" :disabled="disabled" :options="options" @change="onChange"/>
  <a-select
      v-else
      v-model="selected"
      show-arrow allow-clear show-search
      :max-tag-count="3"
      :multiple="multiple"
      :options="options"
      :loading="loading"
      :placeholder="placeholder"
      :disabled="disabled"
      @click="loadOptions"
      @change="onChange"
  ></a-select>
</template>

<script setup lang="ts" name="smart-dict">
import {reactive, toRefs, watch} from 'vue'
import {EmptyUtil, MsgUtil, RequestUtil} from '@/utils'
import {userDictStore} from "@/libs/store";
import {SysConfig} from "@/libs/config";

const dictStore = userDictStore()

const props = defineProps({
  dataList: {
    type: Array,
    required: false,
    default: () => [],
  },

  url: {
    type: String,
    required: false,
    default: null,
  },


  modelValue: {
    type: [String, Number, Object, Boolean],
    required: false,
    default: null,
  },
  disabled: {
    type: Boolean,
    required: false,
    default: false,
  },

  isRadio: {
    type: Boolean,
    required: false,
    default: false,
  },
  placeholder: {
    type: String,
    required: false,
    default: '请选择',
  },
  multiple: {
    type: Boolean,
    required: false,
    default: false,
  },


})

const emit = defineEmits(['update:modelValue', 'change'])

// 当初始值为 空 未定义 或者空字符串时 数据懒加载
const lazyLoad = props.modelValue === null || props.modelValue === undefined || props.modelValue === ''

const state = reactive({
  options: [],
  loading: false,
  disabled: props.disabled,
  placeholder: props.placeholder,
  selected: props.modelValue,
  multiple: props.multiple,
})

const {options, selected, loading} = toRefs(state)

//
const onChange = (e) => emit('update:modelValue', e)

const loadOptions = async () => {
  if (props.dataList.length > 0) {
    state.options = props.dataList

  } else {
    const {url} = props
    // 地址验证
    if (EmptyUtil.isEmptyString(url)) {
      MsgUtil.notify("操作失败", "数据字典缺少请求地址参数", "error")
      return
    }
    // 判断是否允许缓存 允许缓存的路径且当前路径不存在请求参数
    const allowCache = SysConfig.allowCacheUrls.findIndex(x => url.includes(x)) >= 0 && props.url.includes("?") === false

    if (allowCache) {
      // 允许缓存

      const cacheDict = dictStore.readCache(url);
      if (EmptyUtil.isNotEmptyArray(cacheDict)) {
        state.options = cacheDict
        return
      }

    }


    state.loading = true
    const {data} = await RequestUtil.getAjax(props.url)
    state.options = data
    state.loading = false
    if (allowCache) dictStore.putCache(url, data)

  }
}

// 不是懒加载 或 使用 radio标签时 装载组件时初始化字典下拉选项
if (EmptyUtil.isNotEmptyString(props.url) && (!lazyLoad || props.isRadio)) loadOptions()


watch(() => props.modelValue, (x, y) => {
  if (x !== y) state.selected = x
})
</script>

